//
//  SEGCreateActivityViewController.m
//  ExcellentHome
//
//  Created by 陈区 on 13-11-21.
//  Copyright (c) 2013年 陈区. All rights reserved.
//

#import "SEGCreateActivityViewController.h"
#import "SEGOtherCreatActivityRootListViewController.h"

#if __has_include(<commonThirds/SEGImagePickerManager.h>)
#import <commonThirds/SEGImagePickerManager.h>
#else
#import "SEGImagePickerManager.h"
#endif

#import <UIButton+WebCache.h>

@interface SEGCreateActivityViewController () <SEGImagePickerManagerDelegate>

@property (nonatomic, retain) ActivityRequestModel* activityRequestModel;
@property (nonatomic, strong) SEGImagePickerManager *imagePicker;

@end

@implementation SEGCreateActivityViewController
@synthesize imageData;
@synthesize activityModel = m_ActivityModel;
@synthesize tmpStartTmieStr, timeStr;

- (void)loadView
{
    UIScreen* scr = [UIScreen mainScreen];
    CGRect appbounds = CGRectMake(0, 0, scr.bounds.size.width, scr.bounds.size.height - kNavigationBarAndStatusBarHeight);
    UIView* mainView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, appbounds.size.width, appbounds.size.height)];

    m_tableView = [[UITableView alloc] initWithFrame:appbounds style:UITableViewStyleGrouped];
    m_tableView.delegate = self;
    m_tableView.dataSource = self;
    m_tableView.backgroundColor = [UIColor clearColor];
    m_tableView.backgroundView = nil;

    [mainView addSubview:m_tableView];

    CGRect pickViewRect = appbounds;
    pickViewRect.size.height = 256;
    pickViewRect.origin.y = appbounds.size.height;

    datePickerView = [[DatePickerView alloc] initWithFrame:pickViewRect];
    datePickerView.delegate = self;
    NSDate* now = [NSDate date];
    [datePickerView.datePicker setDate:now animated:YES];
    datePickerView.datePicker.minimumDate = now;

    self.view = mainView;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(onKeyboardWillHideNotification:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(onKeyboardWillShowNotification:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(onKeyboardDidShowNotification:)
                                                 name:UIKeyboardDidShowNotification
                                               object:nil];

    isCanEdit = YES;

    [self showCustomNavigationBackButton];

    if (self.activityModel) { //是修改
        self.title = @"编辑活动";
        m_tmpStartTime = [NSDate date];
        m_tmpTime = [NSDate date];

        if ([self.activityModel.status intValue] == kActivityStatePublish) {

            [self showCustomNavigationRightButtonWithTitle:@"保存"
                                                     image:[UIImage imageWithContentsOfFile:SEGPicName(@"common_btn_navbar_right_nor")]
                                           hightlightImage:[UIImage imageWithContentsOfFile:SEGPicName(@"common_btn_navbar_right_pre")]];
        }
        else if ([self.activityModel.status intValue] == kActivityStateStart) {
            isCanEdit = NO;
        }

        UIButton* deleteButton = [[UIButton alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.view.bounds) - 50, LYScreenWidth(), 50)];
        [deleteButton setTitle:@"删除活动" forState:UIControlStateNormal];
        [deleteButton setTitleColor:kColor_W forState:UIControlStateNormal];
        [deleteButton setBackgroundColor:kColor_S1];
        [deleteButton addTarget:self action:@selector(deleteActivity) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:deleteButton];
    }
    else { //是新建
        self.title = @"发起活动";
        [self showCustomNavigationRightButtonWithTitle:@"发布" image:[UIImage imageWithContentsOfFile:@""] hightlightImage:nil color:kColor_T];

        m_tmpStartTime = [NSDate date];
        m_tmpTime = [NSDate date];
        self.activityModel = [[ActivityModel alloc] init];
        self.activityModel.activityNum = [NSNumber numberWithInt:0];
    }
}

#pragma mark -
#pragma mark Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView
{
    // Return the number of sections.
    return 5;
}
- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return 1;
}

- (CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section
{
    switch (section) {
    case 0:
    case 3:
    case 4:
        return 30;
        break;
    default:
        return 0.1;

        break;
    }
}

- (CGFloat)tableView:(UITableView*)tableView heightForFooterInSection:(NSInteger)section;
{

    switch (section) {
    case 2:
    case 3:
        return 0.1;
        break;
    default:
        return 20;
        break;
    }
}

- (UIView*)tableView:(UITableView*)tableView viewForHeaderInSection:(NSInteger)section
{

    UILabel* title = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, 80, 30)];
    title.font = [UIFont systemFontOfSize:FONT_DESCRIPTION_SIZE];
    title.backgroundColor = [UIColor clearColor];
    title.textColor = kColor_3;

    switch (section) {
    case 0:
        title.text = @"     活动图片";
        break;
    case 3:
        title.text = @"     选填";
        break;
    case 4:
        title.text = @"     描述";
        break;

    default:
        break;
    }
    return title;
}

- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
{

    float retHeight = 44;
    switch (indexPath.section) {
    case 0: {
        retHeight = 130;
        break;
    }
    case 2: {
        if (self.activityModel.endDate) {
            retHeight = 44 * 2;
        }
        else {
            retHeight = 44 * 3;
        }
        break;
    }
    case 3: {
        retHeight = 44;
        break;
    }
    case 4: {
        retHeight = 110;
        break;
    }
    }

    return retHeight;
}

- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
    NSString* cellIdentifier = [NSString stringWithFormat:@"cell %ld %ld", (long)indexPath.section, (long)indexPath.row];

    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        cell.backgroundColor = [UIColor whiteColor];

        switch (indexPath.section) {

        case 0: {
            btnImage = [UIButton buttonWithType:UIButtonTypeCustom];
            btnImage.frame = CGRectMake(15, 10, 90, 90);
            btnImage.layer.masksToBounds = YES;
            btnImage.layer.cornerRadius = 10.0;
            if (self.activityModel.pic1.length > 0) {
                [btnImage sd_setBackgroundImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@", kClientImageRootURL, self.activityModel.pic1]] forState:UIControlStateNormal placeholderImage:[UIImage imageWithContentsOfFile:SEGPicName(@"addpicture_btn")]];
            }
            else {
                [btnImage setBackgroundImage:[UIImage imageWithContentsOfFile:SEGPicName(@"addpicture_btn")] forState:UIControlStateNormal];
            }

            [btnImage addTarget:self action:@selector(btnTousuImageDataClicked:) forControlEvents:UIControlEventTouchUpInside];
            btnImage.enabled = isCanEdit;
            [cell.contentView addSubview:btnImage];

            UILabel* desc = [[UILabel alloc] initWithFrame:CGRectMake(20, 105, 290, 20)];
            desc.font = [UIFont systemFontOfSize:FONT_DESCRIPTION_SIZE];
            desc.backgroundColor = [UIColor clearColor];
            desc.text = @"上传活动照片,会更容易找到活动小伙伴哦";
            desc.textColor = kColor_3;
            [cell.contentView addSubview:desc];

            break;
        }

        case 1: {
            UILabel* leftLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, 92, 44)];
            [leftLabel setTextColor:kColor_2];
            [leftLabel setText:@"活动名称"];
            leftLabel.font = [UIFont systemFontOfSize:FONT_LIST_AND_DETAIL_SIZE];
            [leftLabel setBackgroundColor:[UIColor clearColor]];
            [cell.contentView addSubview:leftLabel];

            tfName = [[UITextField alloc] initWithFrame:CGRectMake(100, 0, 190, 44)];
            tfName.backgroundColor = [UIColor clearColor];
            tfName.userInteractionEnabled = YES;
            tfName.tintColor = kColor_T;
            tfName.font = [UIFont systemFontOfSize:FONT_LIST_AND_DETAIL_SIZE];
            [tfName setAttributedPlaceholder:[[NSAttributedString alloc] initWithString:@"请填写活动名称" attributes:@{NSForegroundColorAttributeName:UIColor.grayColor}]];
            tfName.textColor = kColor_1;
            tfName.textAlignment = NSTextAlignmentLeft;
            tfName.returnKeyType = UIReturnKeyDone;
            tfName.delegate = self;
            tfName.text = self.activityModel.name;
            tfName.enabled = isCanEdit;
            [cell.contentView addSubview:tfName];

            break;
        }
        case 2: {
            UILabel* leftLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, 92, 44)];
            [leftLabel setTextColor:kColor_2];
            [leftLabel setText:@"开始时间"];
            leftLabel.font = [UIFont systemFontOfSize:FONT_LIST_AND_DETAIL_SIZE];
            [leftLabel setBackgroundColor:[UIColor clearColor]];
            [cell.contentView addSubview:leftLabel];

            btnBegin = [[UIButton alloc] initWithFrame:CGRectMake(100, 0, LYScreenWidth() - 120, 44)];
            [btnBegin addTarget:self action:@selector(btnBeginZXDateClicked:) forControlEvents:UIControlEventTouchUpInside];
            btnBegin.backgroundColor = [UIColor clearColor];
            [btnBegin setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];

            if (self.activityModel.startDate) {
                [btnBegin setTitle:[self.activityModel.startDate substringToIndex:10] forState:UIControlStateNormal];
                [btnBegin setTitleColor:kColor_1 forState:UIControlStateNormal];
            }
            else {
                [btnBegin setTitle:@"请填写报名开始时间" forState:UIControlStateNormal];
                [btnBegin setTitleColor:kColor_3 forState:UIControlStateNormal];
            }

            [btnBegin.titleLabel setFont:[UIFont systemFontOfSize:FONT_LIST_AND_DETAIL_SIZE]];

            btnBegin.enabled = isCanEdit;
            [cell.contentView addSubview:btnBegin];

            CGRect cellBounds = CGRectMake(10, 43, cell.bounds.size.width, 0.5);
            UIImageView* linebg = [[UIImageView alloc] initWithFrame:cellBounds];
            linebg.width = LYScreenWidth() - 20;
            linebg.image = [UIImage imageWithContentsOfFile:SEGPicName(@"common_line610px.png")];
            [cell.contentView addSubview:linebg];

            UILabel* leftLabel2 = [[UILabel alloc] initWithFrame:CGRectMake(20, 44, 92, 44)];
            [leftLabel2 setTextColor:kColor_2];
            [leftLabel2 setText:@"结束时间"];
            leftLabel2.font = [UIFont systemFontOfSize:FONT_LIST_AND_DETAIL_SIZE];
            [leftLabel2 setBackgroundColor:[UIColor clearColor]];
            [cell.contentView addSubview:leftLabel2];

            btnEnd = [[UIButton alloc] initWithFrame:CGRectMake(100, 44, LYScreenWidth() - 120, 44)];
            [btnEnd addTarget:self action:@selector(btnEndZXDateClicked:) forControlEvents:UIControlEventTouchUpInside];
            btnEnd.backgroundColor = [UIColor clearColor];
            [btnEnd setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
            if (self.activityModel.endDate) {
                [btnEnd setTitle:[self.activityModel.endDate substringToIndex:10] forState:UIControlStateNormal];
                [btnEnd setTitleColor:kColor_1 forState:UIControlStateNormal];
            }
            else {
                [btnEnd setTitle:@"请填写报名结束时间(选填)" forState:UIControlStateNormal];
                [btnEnd setTitleColor:kColor_3 forState:UIControlStateNormal];
            }
            [btnEnd.titleLabel setFont:[UIFont systemFontOfSize:FONT_LIST_AND_DETAIL_SIZE]];
            btnEnd.enabled = isCanEdit;
            [cell.contentView addSubview:btnEnd];

            if (!self.activityModel.endDate) {
                CGRect cellBounds1 = CGRectMake(10, 87, cell.bounds.size.width, 0.5);
                UIImageView* linebg1 = [[UIImageView alloc] initWithFrame:cellBounds1];
                linebg1.image = [UIImage imageWithContentsOfFile:SEGPicName(@"common_line610px.png")];
                linebg1.width = LYScreenWidth() - 20;
                [cell.contentView addSubview:linebg1];

                UILabel* leftLabel1 = [[UILabel alloc] initWithFrame:CGRectMake(20, 88, 92, 44)];
                [leftLabel1 setTextColor:kColor_2];
                [leftLabel1 setText:@"活动时间"];
                leftLabel1.font = [UIFont systemFontOfSize:FONT_LIST_AND_DETAIL_SIZE];
                [leftLabel1 setBackgroundColor:[UIColor clearColor]];
                [cell.contentView addSubview:leftLabel1];

                btnStart = [[UIButton alloc] initWithFrame:CGRectMake(100, 88, LYScreenWidth() - 120, 44)];
                [btnStart addTarget:self action:@selector(btnStartZXDateClicked:) forControlEvents:UIControlEventTouchUpInside];
                [btnStart setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];

                [btnStart setTitle:@"请填写活动开始时间(选填)" forState:UIControlStateNormal];
                self.tmpStartTmieStr = [m_tmpStartTime stringValueWithFormatString:@"yyyy.MM.dd HH:mm"];
                [btnStart.titleLabel setFont:[UIFont systemFontOfSize:FONT_LIST_AND_DETAIL_SIZE]];
                [btnStart setTitleColor:kColor_3 forState:UIControlStateNormal];
                btnStart.enabled = isCanEdit;
                [cell.contentView addSubview:btnStart];
            }

            break;
        }

        case 3: {
            UILabel* leftLabel1 = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, 92, 44)];
            [leftLabel1 setTextColor:kColor_2];
            [leftLabel1 setText:@"总人数"];
            leftLabel1.font = [UIFont systemFontOfSize:FONT_LIST_AND_DETAIL_SIZE];
            [leftLabel1 setBackgroundColor:[UIColor clearColor]];
            [cell.contentView addSubview:leftLabel1];

            tfTotalPeople = [[UITextField alloc] initWithFrame:CGRectMake(100, 0, 190, 44)];
            tfTotalPeople.backgroundColor = [UIColor clearColor];
            tfTotalPeople.userInteractionEnabled = YES;
            tfTotalPeople.font = [UIFont systemFontOfSize:FONT_LIST_AND_DETAIL_SIZE];
            [tfTotalPeople setAttributedPlaceholder:[[NSAttributedString alloc] initWithString:@"请填写总人数" attributes:@{NSForegroundColorAttributeName:kColor_3}]];
            [tfTotalPeople setTintColor:kColor_T];
            tfTotalPeople.textColor = kColor_1;
            tfTotalPeople.keyboardType = UIKeyboardTypeNumberPad;
            tfTotalPeople.textAlignment = NSTextAlignmentLeft;
            tfTotalPeople.returnKeyType = UIReturnKeyDone;
            tfTotalPeople.delegate = self;
            tfTotalPeople.text = [self.activityModel.personNum stringValue];
            tfTotalPeople.enabled = isCanEdit;
            [cell.contentView addSubview:tfTotalPeople];
            break;
        }

        case 4: {

            tvDesc = [[UITextView alloc] initWithFrame:CGRectMake(10, 8, 300, 95)];
            tvDesc.font = [UIFont systemFontOfSize:FONT_LIST_AND_DETAIL_SIZE];
            tvDesc.tintColor = kColor_T;
            tvDesc.textAlignment = NSTextAlignmentLeft;
            tvDesc.returnKeyType = UIReturnKeyDone;
            [tvDesc.layer setCornerRadius:10];
            tvDesc.layer.masksToBounds = YES;
            if (self.activityModel.desc) {
                tvDesc.text = self.activityModel.desc;
                tvDesc.textColor = kColor_2;
            }
            else {
                tvDesc.text = @"可以填写活动地点、条件、费用等";
                tvDesc.textColor = [UIColor grayColor];
            }
            tvDesc.delegate = self;
            tvDesc.editable = isCanEdit;
            [cell.contentView addSubview:tvDesc];

            break;
        }
        }
    }

    return cell;
}

#pragma mark - pickview event
- (void)showDatePickerView
{
    if (m_isShowDatePickerView) {
        return;
    }

    [tfName resignFirstResponder];
    [tfAddr resignFirstResponder];
    [tfCondition resignFirstResponder];
    [tfFeiYong resignFirstResponder];
    [tfTotalPeople resignFirstResponder];
    [tvDesc resignFirstResponder];

    m_isShowDatePickerView = YES;
    UIWindow* window = [[UIApplication sharedApplication].delegate window];

    UIScreen* scr = [UIScreen mainScreen];
    CGRect appbounds = CGRectMake(0, 0, scr.bounds.size.width, scr.bounds.size.height);

    //显示

    [window addSubview:datePickerView];
    datePickerView.hidden = NO;

    [UIView animateWithDuration:0.15
        animations:^{
            CGRect pickViewRect = appbounds;
            pickViewRect.origin.y = appbounds.size.height - datePickerView.frame.size.height;
            pickViewRect.size.height = datePickerView.frame.size.height;
            datePickerView.frame = pickViewRect;

        }
        completion:^(BOOL finished){
        }];
}

- (void)hideDatePickerView
{
    if (!m_isShowDatePickerView) {
        return;
    }
    m_isShowDatePickerView = NO;

    UIScreen* scr = [UIScreen mainScreen];
    CGRect appbounds = CGRectMake(0, 0, scr.bounds.size.width, scr.bounds.size.height);

    [UIView animateWithDuration:0.4
        animations:^{
            CGRect pickViewRect = appbounds;
            pickViewRect.origin.y = appbounds.size.height;
            pickViewRect.size.height = datePickerView.frame.size.height;
            datePickerView.frame = pickViewRect;

        }
        completion:^(BOOL finished) {
            [datePickerView removeFromSuperview];
        }];
}

#pragma mark - datePickerView Delegate

- (void)didDatePickerViewCancelClicked:(DatePickerView*)aPickerView
{
    [self hideDatePickerView];
}

- (void)didDatePickerViewDoneClicked:(DatePickerView*)aPickerView
{
    if (isBegin) {
        self.activityModel.startDate = [SEGUtils stringDateByFormatString:kTimeFormatStringSec withDate:[aPickerView selectDate]];
        [btnBegin setTitle:[SEGUtils stringDateByFormatString:kTimeFormatStringMonth withDate:[aPickerView selectDate]] forState:UIControlStateNormal];
        [btnBegin setTitleColor:kColor_1 forState:UIControlStateNormal];
    }
    if (isEnd) {
        self.activityModel.endDate = [SEGUtils stringDateByFormatString:kTimeFormatStringSec withDate:[aPickerView selectDate]];
        [btnEnd setTitle:[SEGUtils stringDateByFormatString:kTimeFormatStringMonth withDate:[aPickerView selectDate]] forState:UIControlStateNormal];
        [btnEnd setTitleColor:kColor_1 forState:UIControlStateNormal];
    }
    if (isStart) {
        m_tmpStartTime = [aPickerView selectDate];
        [btnStart setTitle:[SEGUtils stringDateByFormatString:@"yyyy-MM-dd  HH:mm" withDate:m_tmpStartTime] forState:UIControlStateNormal];
        self.tmpStartTmieStr = [m_tmpStartTime stringValueWithFormatString:@"MM.dd HH:mm"];
        [btnStart setTitleColor:kColor_1 forState:UIControlStateNormal];
    }
    if (isTime) {
        m_tmpTime = [aPickerView selectDate];
        [btnStartTime setTitle:[SEGUtils stringDateByFormatString:@"HH:mm" withDate:m_tmpTime] forState:UIControlStateNormal];
        self.timeStr = [m_tmpTime stringValueWithFormatString:@"HH:mm"];
        [btnStartTime setTitleColor:kColor_1 forState:UIControlStateNormal];
    }
    NSDate* startDate = [SEGUtils dateFromString:self.activityModel.startDate withFormatString:kTimeFormatStringSec];
    NSDate* endDate = [SEGUtils dateFromString:self.activityModel.endDate withFormatString:kTimeFormatStringSec];
    if ([startDate timeIntervalSinceDate:endDate] > 0) {

        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:@"活动开始时间不能大于结束时间"
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
        return;
    }

    [self hideDatePickerView];
}

#pragma mark - UIButton Event
- (void)deleteActivity
{
    [self.activityRequestModel requestDeleteActivityWithId:[self.activityModel.serviceId stringValue] finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        if (isSuccessed) { //数据返回正常
            [[NSNotificationCenter defaultCenter] postNotificationName:REQUEST_ACTIVITY_CREATE_SUCCESS
                                                                object:nil
                                                              userInfo:nil];
            //修改成功，返回界面
            NSArray* VCArr = self.navigationController.viewControllers;
            for (int i = 0; i < VCArr.count; i++) {
                UIViewController* viewController = VCArr[i];
                if ([viewController isKindOfClass:[SEGOtherCreatActivityRootListViewController class]]) {
                    [self.navigationController popToViewController:viewController animated:YES];
                    return;
                }
            }
            [self.navigationController popViewControllerAnimated:YES];
        }
        else {
            UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@""
                                                            message:
                                                                [result objectForKey:@"message"]
                                                           delegate:nil
                                                  cancelButtonTitle:NSLocalizedString(@"确定", @"")
                                                  otherButtonTitles:nil];
            [alert show];

            [curTextField endEditing:YES];
        }
    }];
}

- (void)btnBeginZXDateClicked:(UIButton*)sender
{
    datePickerView.datePicker.datePickerMode = UIDatePickerModeDate;
    [self showDatePickerView];
    isEnd = NO;
    isBegin = YES;
    isStart = NO;
    isTime = NO;
}
- (void)btnEndZXDateClicked:(UIButton*)sender
{
    datePickerView.datePicker.datePickerMode = UIDatePickerModeDate;
    [self showDatePickerView];
    isEnd = YES;
    isBegin = NO;
    isStart = NO;
    isTime = NO;
}

- (void)btnStartZXDateClicked:(UIButton*)sender
{
    datePickerView.datePicker.datePickerMode = UIDatePickerModeDateAndTime;
    [self showDatePickerView];
    isEnd = NO;
    isBegin = NO;
    isStart = YES;
    isTime = NO;
}

- (void)btnTousuImageDataClicked:(UIButton*)sender
{
    [tfName resignFirstResponder];
    [tfAddr resignFirstResponder];
    [tfCondition resignFirstResponder];
    [tfFeiYong resignFirstResponder];
    [tfTotalPeople resignFirstResponder];
    [tvDesc resignFirstResponder];

    UIActionSheet* actionSheetView = nil;
    //判断是否有摄像头
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        actionSheetView = [[UIActionSheet alloc] initWithTitle:nil
                                                      delegate:self
                                             cancelButtonTitle:@"取消"
                                        destructiveButtonTitle:nil
                                             otherButtonTitles:@"拍照", @"相册", nil]; //,@"视频",nil];
    }
    else {
        actionSheetView = [[UIActionSheet alloc] initWithTitle:nil
                                                      delegate:self
                                             cancelButtonTitle:@"取消"
                                        destructiveButtonTitle:nil
                                             otherButtonTitles:@"相册", nil];
    }
    actionSheetView.tag = 120;
    [actionSheetView showInView:self.view];
}

#pragma mark 发布按钮
- (void)onNavigationRightButtonClicked:(UIButton*)sender
{

    if (self.activityModel && [[self.activityModel.issuePerson stringValue] isEqualToString:kAccountUserID]) { //修改

        //保存值之前，先保存值
        [curTextField endEditing:YES];
        [curTextView endEditing:YES];

        

        [self requestUpdateActivity];
    }
    else { //发起

        //保存值之前，先保存值
        [curTextField endEditing:YES];
        [curTextView endEditing:YES];

        if ([self.activityModel.name length] == 0) {
            UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@""
                                                            message:@"请填写活动名称"
                                                           delegate:nil
                                                  cancelButtonTitle:NSLocalizedString(@"确定", @"")
                                                  otherButtonTitles:nil];
            [alert show];
            return;
        }

        if ([self.activityModel.startDate length] == 0) {
            UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@""
                                                            message:@"请填写活动开始时间"
                                                           delegate:nil
                                                  cancelButtonTitle:NSLocalizedString(@"确定", @"")
                                                  otherButtonTitles:nil];
            [alert show];
            return;
        }

        //        if ([self.activityModel.endDate length] == 0) {
        //            UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@""
        //                                                            message:@"请填写活动结束时间"
        //                                                           delegate:nil
        //                                                  cancelButtonTitle:NSLocalizedString(@"确定", @"")
        //                                                  otherButtonTitles:nil];
        //            [alert show];
        //            [alert release];
        //            return;
        //        }
        //
        //        if (!self.activityModel.totalPersonNum) {
        //            UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@""
        //                                                            message:@"请填写活动总人数"
        //                                                           delegate:nil
        //                                                  cancelButtonTitle:NSLocalizedString(@"确定", @"")
        //                                                  otherButtonTitles:nil];
        //            [alert show];
        //            [alert release];
        //            return;
        //        }

        if ([self.activityModel.desc length] == 0) {
            UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@""
                                                            message:@"请填写活动详情"
                                                           delegate:nil
                                                  cancelButtonTitle:NSLocalizedString(@"确定", @"")
                                                  otherButtonTitles:nil];
            [alert show];
            return;
        }
        
//        NSInteger len = [self.activityModel.desc length];
//        if (len != [[self.activityModel.desc segFilterEmoji] length]) {
//            [SEGAlertView showTmepMessageWithMessage:@"发布活动暂时不支持表情！"];
//            return;
//        }
        //        [self jointDesc];
        // 发布活动
        

        [self requestCreateActivity];
    }
}

- (void)onNavigationLeftButtonClicked:(UIButton*)sender
{
    [self hideDatePickerView];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - UIActionSheetDelegate

- (void)actionSheet:(UIActionSheet*)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //判断是否有摄像头
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        if (buttonIndex == 0) {
            self.imagePicker = [[SEGImagePickerManager alloc] init];
            self.imagePicker.delegate = self;
            self.imagePicker.sourceType = SEGImagePickerManagerSourceTypeCamera;
            self.imagePicker.allowsEditing = NO;
            self.imagePicker.maxImagesCount = 1;
            [self.imagePicker presentImagePickerControllerWithAnimated:YES completion:nil];
        }
        else if (buttonIndex == 1) {
            self.imagePicker = [[SEGImagePickerManager alloc] init];
            self.imagePicker.delegate = self;
            self.imagePicker.sourceType = SEGImagePickerManagerSourceTypePhotoLibrary;
            self.imagePicker.allowsEditing = YES;
            self.imagePicker.maxImagesCount = 1;
            [self.imagePicker presentImagePickerControllerWithAnimated:YES completion:nil];
        }
    }
    else {
        if (buttonIndex == 0) {
            self.imagePicker = [[SEGImagePickerManager alloc] init];
            self.imagePicker.delegate = self;
            self.imagePicker.sourceType = SEGImagePickerManagerSourceTypePhotoLibrary;
            self.imagePicker.allowsEditing = YES;
            self.imagePicker.maxImagesCount = 1;
            [self.imagePicker presentImagePickerControllerWithAnimated:YES completion:nil];
        }
    }
}

#pragma mark - <SEGImagePickerManagerDelegate>
- (void)seg_imagePickerManagerDidCancel:(SEGImagePickerManager *)picker {
    
}

- (void)seg_imagePickerManager:(SEGImagePickerManager *)manager didFinishPickingPhotos:(NSArray<UIImage *> *)photos assets:(NSArray<PHAsset *> *)assets isSelectOriginalPhoto:(BOOL)isSelect {
    
    UIImage* img = photos.lastObject;
    NSUInteger len = [UIImageJPEGRepresentation(img, 1) length];
    if (len > 204800) { //字节数大于200k，就开始压缩
        img = [UIImage imageWithData:UIImageJPEGRepresentation(img, 204800.0 / len)];
    }
    
    self.imageData = [NSData dataWithData:UIImageJPEGRepresentation(img, 1.0)];
    [btnImage setBackgroundImage:img forState:UIControlStateNormal];
}

#pragma mark - TextField Delegate

- (BOOL)textFieldShouldBeginEditing:(UITextField*)textField
{
    curTextField = textField;
    CGRect parentRect = [textField convertRect:textField.bounds toView:m_tableView];
    [m_tableView setContentOffset:CGPointMake(0, parentRect.origin.y - 100) animated:YES];

    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField*)textField
{
    doneInKeyboardButton.hidden = YES;
    showDoneInKeyboard = NO;
}

- (void)textFieldDidEndEditing:(UITextField*)textField
{
    curTextField = nil;

    if (textField == tfName) {
        self.activityModel.name = textField.text;
    }
    else if (textField == tfAddr) {
        self.activityModel.place = textField.text;
    }
    else if (textField == tfCondition) {
        self.activityModel.brief = textField.text;
    }
    else if (textField == tfFeiYong) {
        self.activityModel.sellingPrice = textField.text;
    }
    else if (textField == tfTotalPeople) {
        self.activityModel.totalPersonNum = [NSNumber numberWithInt:[textField.text intValue]];
    }
}

- (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)string
{
    if ([string isEqualToString:@"\n"]) {
        [textField resignFirstResponder];
        return NO;
    }

    NSString* text = [NSString stringWithFormat:@"%@%@", textField.text, string];

    if (textField == tfName && [text length] >= 16) {
        return NO;
    }
    else if (textField == tfAddr && [text length] >= 16) {
        return NO;
    }
    else if (textField == tfCondition && [text length] >= 16) {
        return NO;
    }
    else if (textField == tfFeiYong && [text length] >= 16) {
        return NO;
    }
    else if (textField == tfTotalPeople && [text length] >= 16) {
        return NO;
    }
    return YES;
}

#pragma mark - pickview event

- (void)textViewDidBeginEditing:(UITextView*)textView
{
    CGRect parentRect = [textView convertRect:textView.bounds toView:m_tableView];
    [m_tableView setContentOffset:CGPointMake(0, parentRect.origin.y - 100) animated:YES];

    doneInKeyboardButton.hidden = YES;
    showDoneInKeyboard = NO;

    curTextView = textView;
    if ([self.activityModel.desc length] == 0) {
        textView.text = @"";
        textView.textColor = kColor_2;
    }
}
- (void)textViewDidEndEditing:(UITextView*)textView
{

    self.activityModel.desc = textView.text;

    curTextView = nil;
    if ([self.activityModel.desc length] == 0) {
        textView.text = @"请输入活动详情，限定200个字内";
        textView.textColor = [UIColor grayColor];
    }
}

- (BOOL)textView:(UITextView*)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString*)text
{
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }

    NSString* string = [NSString stringWithFormat:@"%@%@", textView.text, text];

    if (textView == tvDesc && [string length] >= 200) {
        return NO;
    }
    return YES;
}

#pragma mark - notitication
- (void)onKeyboardWillHideNotification:(NSNotification*)aNotification
{

    //隐藏dome按钮
    if (doneInKeyboardButton.superview) {
        [doneInKeyboardButton removeFromSuperview];
    }

    UIView* curInputView = nil;
    if (curTextField) {
        curInputView = curTextField;
    }
    else if (curTextView) {
        curInputView = curTextView;
    }

    UIScreen* scr = [UIScreen mainScreen];
    CGRect appbounds = CGRectMake(0, 0, scr.bounds.size.width, scr.bounds.size.height - kNavigationBarAndStatusBarHeight);
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.3];

    m_tableView.frame = appbounds;

    [m_tableView scrollRectToVisible:[curInputView convertRect:curInputView.frame toView:m_tableView] animated:YES];

    [UIView commitAnimations];
}

- (void)onKeyboardWillShowNotification:(NSNotification*)aNotification
{
    [self hideDatePickerView];

    UIView* curInputView = nil;
    if (curTextField) {
        curInputView = curTextField;
    }
    else if (curTextView) {
        curInputView = curTextView;
    }

    CGSize kbSize = [[[aNotification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;

    UIScreen* scr = [UIScreen mainScreen];
    CGRect appbounds = CGRectMake(0, 0, scr.bounds.size.width, scr.bounds.size.height - kNavigationBarAndStatusBarHeight);
    appbounds.size.height -= kbSize.height;

    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.3];

    m_tableView.frame = appbounds;

    [m_tableView scrollRectToVisible:[curInputView convertRect:curInputView.frame toView:m_tableView] animated:YES];

    [UIView commitAnimations];
}

- (void)onKeyboardDidShowNotification:(NSNotification*)aNotification
{
    if (doneInKeyboardButton == nil) {
        doneInKeyboardButton = [UIButton buttonWithType:UIButtonTypeCustom];
        if (LYScreenHeight() == 568.0f) { //爱疯5
            doneInKeyboardButton.frame = CGRectMake(0, 568 - 53, 106, 53);
        }
        else { //3.5寸
            doneInKeyboardButton.frame = CGRectMake(0, 480 - 53, 106, 53);
        }

        doneInKeyboardButton.adjustsImageWhenHighlighted = NO;
        //图片直接抠腾讯财付通里面的= =!
        [doneInKeyboardButton setImage:[UIImage imageWithContentsOfFile:SEGPicName(@"common_btn_keyboard_done_up")] forState:UIControlStateNormal];
        [doneInKeyboardButton setImage:[UIImage imageWithContentsOfFile:SEGPicName(@"common_btn_keyboard_done_down")] forState:UIControlStateHighlighted];
        [doneInKeyboardButton addTarget:self action:@selector(finishAction) forControlEvents:UIControlEventTouchUpInside];
    }

    UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];

    if (doneInKeyboardButton.superview == nil) {
        [tempWindow addSubview:doneInKeyboardButton]; // 注意这里直接加到window上
    }

    if (showDoneInKeyboard) {
        doneInKeyboardButton.hidden = NO;
    }
    else {
        doneInKeyboardButton.hidden = YES;
    }
}

- (void)finishAction
{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES]; //关闭键盘
}

//拼接字符串
- (void)jointDesc
{
    self.activityModel.desc = [NSString stringWithFormat:@"此活动于%@开始。\n%@", self.tmpStartTmieStr, self.activityModel.desc];
}

#pragma mark - request
// 请求发起活动
- (void)requestCreateActivity
{
    [SVProgressHUD show];
    [self.activityRequestModel requestCreateActivityWithActivityModel:self.activityModel imageData:self.imageData finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        [SVProgressHUD dismiss];
        if (isSuccessed) { //数据返回正常
            //创建成功，返回界面
            UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@""
                                                            message:@"发布成功"
                                                           delegate:nil
                                                  cancelButtonTitle:NSLocalizedString(@"确定", @"")
                                                  otherButtonTitles:nil];
            [alert show];

            [self.navigationController popViewControllerAnimated:YES];

            [[NSNotificationCenter defaultCenter] postNotificationName:REQUEST_ACTIVITY_CREATE_SUCCESS
                                                                object:nil
                                                              userInfo:nil];
        }
        else {
            UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@""
                                                            message:errorMessage
                                                           delegate:nil
                                                  cancelButtonTitle:NSLocalizedString(@"确定", @"")
                                                  otherButtonTitles:nil];
            [alert show];
        }

    }];
}

// 请求更新活动
- (void)requestUpdateActivity
{
    
    [self.activityRequestModel requestUpdateActivityWithActivityModel:self.activityModel imageData:imageData finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
    
        if (isSuccessed) { //数据返回正常
            //修改成功，返回界面
            [self.navigationController popViewControllerAnimated:YES];

            [[NSNotificationCenter defaultCenter] postNotificationName:REQUEST_ACTIVITY_JOIN_SUCCESS
                                                                object:nil
                                                              userInfo:nil];
        }
        else {
            UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@""
                                                            message:
                                                                [result objectForKey:@"message"]
                                                           delegate:nil
                                                  cancelButtonTitle:NSLocalizedString(@"确定", @"")
                                                  otherButtonTitles:nil];
            [alert show];

            [curTextField endEditing:YES];
        }
    }];
}

#pragma mark - getter
- (ActivityRequestModel*)activityRequestModel
{
    if (!_activityRequestModel) {
        _activityRequestModel = [[ActivityRequestModel alloc] init];
    }
    return _activityRequestModel;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
